#include "seams.h"

Seams::Seams(int maxSeam)
{
    this->maxSeam = maxSeam;

}
void Seams::addSeam(Seam* seam){
    // add the seam
    queue.push(seam);
    // remove the worse seam if we already have enought seam
    if(queue.size() > maxSeam){
        Seam* tmpSeam = queue.top();
        queue.pop();
        delete tmpSeam;

    }
}

bool Seams::addNotPossible(Seam* seam){
    priority_queue<Seam*> tmpQueue = getSeams();
    int nbPointsSeam = seam->getNbPoints();
    while(!tmpQueue.empty()){
        Seam* tmpSeam = tmpQueue.top();
        tmpQueue.pop();

        for(int i = 0; i < nbPointsSeam; i++){
            if(seam->getPoint(i)->x() == tmpSeam->getPoint(i)->x() &&
               seam->getPoint(i)->y() == tmpSeam->getPoint(i)->y()){

                return true;
            }
        }
    }
    return false;
}


void Seams::clear(){

    while(!queue.empty()){
        Seam* seam = queue.top();
        delete seam;
        queue.pop();
    }
}

// this methode able to get all the element of the queue that are at the position xy
QPoint** Seams::getPoints(int xy){
    QPoint** tableOfPoints = new QPoint*[maxSeam];
    int i = 0;
    priority_queue <Seam*> tmpSeams;
    while(!queue.empty()){
        Seam* seam = queue.top();
        tmpSeams.push(seam);
        queue.pop();

        tableOfPoints[i] = seam->getPoint(xy);
        i++;
    }
    while(!tmpSeams.empty()){
        queue.push(tmpSeams.top());
        tmpSeams.pop();
    }
    // classement of the element in order
    for(int i = 0; i < maxSeam - 1; i++){
        //recherche of the minimum
        int place = i;
        QPoint* min = tableOfPoints[i];
        for(int j = i; j < maxSeam; j++){
            if(min->x() > tableOfPoints[j]->x() || min->y() > tableOfPoints[j]->y()){
                place = j;
                min = tableOfPoints[j];
            }
        }
        // interversion for the min and the value in the table at the position i
        QPoint* tmp = tableOfPoints[i];
        tableOfPoints[i] = tableOfPoints[place];
        tableOfPoints[place] = tmp;
    }

    return tableOfPoints;

}

priority_queue<Seam*> Seams::getSeams(){
    return queue;
}

